package cjq.demo.nio.ch2_4;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.channels.AsynchronousServerSocketChannel;
import java.util.concurrent.CountDownLatch;

/**
 * Created by Administrator on 2016/4/18.
 */
public class AsyncTimeServerHandler implements Runnable {
    private int port;

    CountDownLatch latch ;

    AsynchronousServerSocketChannel asynchronousServerSocketChannel;

    public AsyncTimeServerHandler(int port){
        this.port = port;
        try{
            //创建一个异步的服务端通道
            asynchronousServerSocketChannel = AsynchronousServerSocketChannel.open();
            asynchronousServerSocketChannel.bind(new InetSocketAddress(port));
            System.out.println("The time server is start in port:"+port);
        }catch(IOException e){
            e.printStackTrace();
        }
    }

    public void run(){
        //初始化CountDownLatch对象，
        // 作用是在完成一组正在执行的操作之前，
        // 允许当前的线程一直阻塞
        //在本例程中，我们让线程在此阻塞，防止服务端执行完成退出。
        latch = new CountDownLatch(1);
        doAccept();
        try{
            latch.await();
        }catch(InterruptedException e){
            e.printStackTrace();
        }
    }

    //接收客户端的连接
    //由于是异步操作，要以传递一个CompletionHandler<AsynchronousSocketChannel,? super A>类型的实例接收accept操作成功的通知消息
    private void doAccept() {
        asynchronousServerSocketChannel.accept(this,new AcceptCompletionHandler());
    }
}
